﻿using NAGFwk.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SilkeyERP.UI.Entities.SalesPriceList
{
    public partial class CustomEditContentView : BaseCustomEditForm
    {
        private Model.SalesPriceList current { get; set; }
        private Shared.ProductChooser MyProductSearchForm = new Shared.ProductChooser();

        public CustomEditContentView()
        {
            InitializeComponent();
            SetInitialDataSource();
            btnProductSearch.FormChooserType = MyProductSearchForm;
            btnProductSearch.OnSelected += btnProductSearch_OnSelected;
            EnablextpxtpGroupedSalesPriceList();
            rgManageOneByOne.EditValue = true;
            gvSalesPriceListDetails.BestFitColumns();
            xtcCustomEditContentView.SelectedTabPageIndex = 0;
        }

        private void SetInitialDataSource()
        {
            buyPriceListBindingSource.DataSource = new BL.BuyPriceListController().GetAll();
            productsBindingSource.DataSource = new BL.ProductsController().GetAll();
            taxBindingSource.DataSource = new BL.TaxController().GetAll();
        }

        void btnProductSearch_OnSelected(List<dynamic> SelectedItems)
        {
            AddToSalesPriceListDetails(SelectedItems);
            UpdateSalesPriceListDetails();
        }

        private Model.SalesPriceListDetails AddNewSalesPriceListDetail(int? ProductID)
        {
            var newSPLD = new Model.SalesPriceListDetails()
          {
              SalesPriceListID = current.BuyPriceListID,
              CurrentPriceWOutTax = 0,
              CurrentPriceWTax = 0,
              TaxID = 1,
              Tax = new BL.TaxController().GetByID(1),
              Percentage = (!(bool)rgManageOneByOne.EditValue ? (decimal)seApplyValue.EditValue : 0),
              IsIncrement = (!(bool)rgManageOneByOne.EditValue ? chkIsIncremental.Checked : true),
          };
            if (ProductID.HasValue)
                newSPLD.ProductID = ProductID.Value;

            return newSPLD;
        }

        private void AddToSalesPriceListDetails(List<dynamic> SelectedProducts)
        {            
            var oriResult = ((List<Model.SalesPriceListDetails>)salesPriceListDetailsBindingSource.List);
            foreach (Model.Products SelectedItem in SelectedProducts)
                if (!oriResult.Any(x => x.ProductID == SelectedItem.ProductID))
                    salesPriceListDetailsBindingSource.Add(AddNewSalesPriceListDetail(SelectedItem.ProductID));
        }

        private void EnablextpxtpGroupedSalesPriceList()
        {
            if (cboBuyPriceList.EditValue == null)
                return;
            var salesPriceListId = int.Parse(cboBuyPriceList.EditValue.ToString());

            xtpGroupedSalesPriceList.PageVisible = (salesPriceListId != 0);
        }

        public void InitData(ref Model.SalesPriceList currentSalesPriceList)
        {
            var _currentSalesPriceListDetails = new List<Model.SalesPriceListDetails>();
            if (currentSalesPriceList.SalesPriceListDetails.Count != 0)
                _currentSalesPriceListDetails.AddRange(currentSalesPriceList.SalesPriceListDetails);
            salesPriceListDetailsBindingSource.DataSource = _currentSalesPriceListDetails;
            currentSalesPriceList.SalesPriceListDetails = _currentSalesPriceListDetails;

            current = currentSalesPriceList;

            if (IsNew)
                current.SetNextAvailableSalesPriceList();

            if (IsEdit)
                priceListCodeTextEdit.Enabled = false;
        }

        private void rgManageOneByOne_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetManageSalesPriceListControls();
        }

        private void SetManageSalesPriceListControls()
        {
            if (!xtpGroupedSalesPriceList.PageVisible)
                return;
            var enableCtrls = (bool)rgManageOneByOne.EditValue;
            chkIsIncremental.Enabled = !enableCtrls;
            seApplyValue.Enabled = !enableCtrls;
            btnProductSearch.Enabled = !enableCtrls;
            gcSalesPriceListDetails.UseEmbeddedNavigator = enableCtrls;
        }

        private void cboBuyPriceList_EditValueChanged(object sender, EventArgs e)
        {
            EnablextpxtpGroupedSalesPriceList();
        }

        private void chkIsIncremental_CheckedChanged(object sender, EventArgs e)
        {
            UpdateSalesPriceListDetails();
        }

        private void seApplyValue_EditValueChanged(object sender, EventArgs e)
        {
            UpdateSalesPriceListDetails();
        }

        private void UpdateSalesPriceListDetails()
        {
            if (!(bool)rgManageOneByOne.EditValue)
                foreach (Model.SalesPriceListDetails item in salesPriceListDetailsBindingSource.List)
                {
                    item.Percentage = (decimal)seApplyValue.EditValue;
                    if (chkIsIncremental.Checked)
                    {
                        item.CurrentPriceWTax = ((item.CurrentBuyPriceWTax * item.Percentage) / 100) + item.CurrentBuyPriceWTax;
                        item.CurrentPriceWOutTax = ((item.CurrentBuyPriceWOutTax * item.Percentage) / 100) + item.CurrentBuyPriceWOutTax;
                    }
                    else
                    {
                        item.CurrentPriceWTax = item.CurrentBuyPriceWTax - ((item.CurrentBuyPriceWTax * item.Percentage) / 100);
                        item.CurrentPriceWOutTax = item.CurrentBuyPriceWOutTax - ((item.CurrentBuyPriceWOutTax * item.Percentage) / 100);
                    }
                }
            gcSalesPriceListDetails.RefreshDataSource();
        }

        private void richkIsIncremental_CheckedChanged(object sender, EventArgs e)
        {
            if (salesPriceListDetailsBindingSource.Current != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
                if (typedPriceListDetailsBindingSource.TaxID != 0)
                {
                    UpdateCurrentPriceWOutTax(
                        typedPriceListDetailsBindingSource.CurrentBuyPriceWTax
                        , typedPriceListDetailsBindingSource.TaxID
                        , (bool)((DevExpress.XtraEditors.CheckEdit)sender).EditValue
                        , typedPriceListDetailsBindingSource.Percentage);
                    UpdateCurrentPriceWTax(
                        typedPriceListDetailsBindingSource.CurrentBuyPriceWOutTax
                        , typedPriceListDetailsBindingSource.TaxID
                        , (bool)((DevExpress.XtraEditors.CheckEdit)sender).EditValue
                        , typedPriceListDetailsBindingSource.Percentage);
                }
            }
        }

        private void risePercentage_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListDetailsBindingSource.Current != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
                if (typedPriceListDetailsBindingSource.TaxID != 0 && ((DevExpress.XtraEditors.SpinEdit)sender).EditValue != null)
                {
                    UpdateCurrentPriceWOutTax(
                        typedPriceListDetailsBindingSource.CurrentBuyPriceWTax
                        , typedPriceListDetailsBindingSource.TaxID
                        , typedPriceListDetailsBindingSource.IsIncrement
                        , (decimal)((DevExpress.XtraEditors.SpinEdit)sender).EditValue);
                    UpdateCurrentPriceWTax(
                        typedPriceListDetailsBindingSource.CurrentBuyPriceWOutTax
                        , typedPriceListDetailsBindingSource.TaxID
                        , typedPriceListDetailsBindingSource.IsIncrement
                        , (decimal)((DevExpress.XtraEditors.SpinEdit)sender).EditValue);
                }
            }
        }

        private void rilueTax_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListDetailsBindingSource.Current != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
                if (typedPriceListDetailsBindingSource.TaxID != 0 && ((DevExpress.XtraEditors.LookUpEdit)sender).EditValue != null)
                {
                    UpdateCurrentPriceWOutTax(
                        typedPriceListDetailsBindingSource.CurrentBuyPriceWTax
                        , (int)((DevExpress.XtraEditors.LookUpEdit)sender).EditValue
                        , typedPriceListDetailsBindingSource.IsIncrement
                        , typedPriceListDetailsBindingSource.Percentage);
                    UpdateCurrentPriceWTax(
                        typedPriceListDetailsBindingSource.CurrentBuyPriceWOutTax
                        , (int)((DevExpress.XtraEditors.LookUpEdit)sender).EditValue
                        , typedPriceListDetailsBindingSource.IsIncrement
                        , typedPriceListDetailsBindingSource.Percentage);
                }
            }
        }

        private void riseCurrentPriceWTax_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListDetailsBindingSource.Current != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
                if (typedPriceListDetailsBindingSource.TaxID != 0 && ((DevExpress.XtraEditors.SpinEdit)sender).EditValue != null)
                {
                    var currentSelectedPriceWTax = (decimal)((DevExpress.XtraEditors.SpinEdit)sender).EditValue;

                    typedPriceListDetailsBindingSource.CurrentPriceWTax = currentSelectedPriceWTax;
                    typedPriceListDetailsBindingSource.CurrentPriceWOutTax = currentSelectedPriceWTax / decimal.Parse("1." + typedPriceListDetailsBindingSource.Tax.TaxValue.ToString().Replace(".", ""));
                }
            }
        }

        private void riseCurrentPriceWOutTax_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListDetailsBindingSource.Current != null && ((DevExpress.XtraEditors.SpinEdit)sender).EditValue != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
                if (typedPriceListDetailsBindingSource.TaxID != 0)
                {
                    var currentSelectedPriceWOutTax = (decimal)((DevExpress.XtraEditors.SpinEdit)sender).EditValue;

                    typedPriceListDetailsBindingSource.CurrentPriceWOutTax = currentSelectedPriceWOutTax;
                    typedPriceListDetailsBindingSource.CurrentPriceWTax = currentSelectedPriceWOutTax * decimal.Parse("1." + typedPriceListDetailsBindingSource.Tax.TaxValue.ToString().Replace(".", ""));
                }
            }
        }

       

        private void UpdateCurrentPriceWOutTax(decimal CurrentBuyPriceWTax, int TaxID, bool isIncrement, decimal percentage)
        {
            var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
            var SelectedTaxValue = new BL.TaxController().GetTax(TaxID).TaxValue;
            typedPriceListDetailsBindingSource.CurrentPriceWOutTax = Model.Products.GetSalesValueWOutTax(SelectedTaxValue, isIncrement, percentage, CurrentBuyPriceWTax);
        }

        private void UpdateCurrentPriceWTax(decimal CurrentBuyPriceWOutTax, int TaxID, bool isIncrement, decimal percentage)
        {
            var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
            var SelectedTaxValue = new BL.TaxController().GetTax(TaxID).TaxValue;
            typedPriceListDetailsBindingSource.CurrentPriceWTax = Model.Products.GetSalesValueWTax(SelectedTaxValue, isIncrement, percentage, CurrentBuyPriceWOutTax);
        }      

        private void gcSalesPriceListDetails_EmbeddedNavigator_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case DevExpress.XtraEditors.NavigatorButtonType.Append:
                    salesPriceListDetailsBindingSource.Add(AddNewSalesPriceListDetail(null));
                    e.Handled = true;
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.CancelEdit:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.Custom:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.Edit:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.EndEdit:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.First:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.Last:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.Next:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.NextPage:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.Prev:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.PrevPage:
                    break;
                case DevExpress.XtraEditors.NavigatorButtonType.Remove:
                    break;
                default:
                    break;
            }
        }

        private void rilueProducts_EditValueChanged(object sender, EventArgs e)
        {
            if (salesPriceListDetailsBindingSource.Current != null)
            {
                var typedPriceListDetailsBindingSource = (Model.SalesPriceListDetails)salesPriceListDetailsBindingSource.Current;
                if (((DevExpress.XtraEditors.LookUpEdit)sender).EditValue != null)
                {
                    var buyPriceList = new BL.BuyPriceListController().GetBuyPriceList((int)cboBuyPriceList.EditValue);
                    Model.BuyPriceListDetails currentBuyProduct = buyPriceList.BuyPriceListDetails.Where(x => x.ProductID == (int)((DevExpress.XtraEditors.LookUpEdit)sender).EditValue).SingleOrDefault();

                    if (currentBuyProduct != null)
                    {
                        typedPriceListDetailsBindingSource.TaxID = currentBuyProduct.TaxID;
                        typedPriceListDetailsBindingSource.Tax = currentBuyProduct.Tax;
                    }
                }
            }

        }

        private void gvSalesPriceListDetails_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (((List<Model.SalesPriceListDetails>)salesPriceListDetailsBindingSource.DataSource).Where(x => x.ProductID == ((Model.SalesPriceListDetails)e.Row).ProductID).Count() > 1)
            {
                e.ErrorText = Properties.Resources.ErrorProductDuplicated;
                e.Valid = false;
            }
        }

    }
}
